<style lang="scss">
.item {
  margin-left: 10px;

  .el-badge__content.is-fixed {
    top: 0.5em;
    right: 1.5em;
  }
}

.search-circle {
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  width: 30px;
  height: 30px;
  padding: 0;
  margin-right: 0;
}
</style>

<template>
  <basic-container>
    <div class="search_form">
      <el-form ref="form" :model="queryForm" :rules="rules" label-width="100px" @submit.native.prevent>
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="订单名称:">
              <el-input
                id="id-business-offer-searchForm-two"
                placeholder="请输入订单名称"
                v-model="queryForm.name"
                clearable
                size="mini"
                @keyup.enter.native="searchForm">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="订单ID:" prop="id">
              <el-input id="id-business-offer-searchForm" placeholder="请输入订单ID" size="mini" style="height:24px;"
                        v-model="queryForm.id" clearable
                        @keyup.enter.native="searchForm">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="客户:">
              <el-input
                id="id-business-offer-searchForm-three"
                placeholder="请输入客户"
                v-model="queryForm.customerName"
                clearable
                size="mini"
                @keyup.enter.native="searchForm">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="客户等级:">
              <el-select id="id-business-offer-queryForm-sharedUserId" v-model="queryForm.customerLevel" clearable
                         filterable size="mini" placeholder="请选择客户等级" style="width:100%"
                         ref="sharedUserId" @visible-change="isShowSelectOptions" @change="searchForm">
                <el-option
                  v-for="item in customerLevelList"
                  :key="item.id"
                  :label="item.value"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="4" style="min-width: 160px;display:flex;justify-content:flex-end;float: right">
            <el-tooltip class="item" effect="dark" content="展开全部" placement="top">
              <el-button :class="upIcon" class="search-circle" @click="unfoldIcon"
                         style="margin-right: 10px"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="清空" placement="top">
              <el-button id="id-business-offer-emptyForm" :class="emptyIcon" class="search-circle"
                         @click="emptyForm"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="搜索" placement="top">
              <el-button id="id-business-offer-searchForm-four" type="primary" icon="el-icon-search" size="small"
                         @click="searchForm" style="margin-right: 0">
                搜索
              </el-button>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row v-show="searchConceal" :gutter="20">
          <el-col :span="5">
            <el-form-item label="产品名:">
              <el-input
                id="id-business-offer-queryForm-productName"
                placeholder="请输入产品名"
                v-model="queryForm.productName"
                clearable
                size="mini" @keyup.enter.native="searchForm">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="状态:">
              <el-select id="id-business-offer-queryForm-status" v-model="queryForm.status" clearable size="mini"
                         placeholder="请选择状态" style="width:100%"
                         ref="offerStatus" @visible-change="isShowSelectOptions" @change="searchForm">
                <el-option
                  v-for="item in statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="客户经理:">
              <el-select id="id-business-offer-queryForm-customerManager" v-model="queryForm.customerManager" clearable
                         filterable size="mini" placeholder="请选择客户经理" style="width:100%"
                         ref="customerManager" @visible-change="isShowSelectOptions" @change="searchForm">
                <el-option
                  v-for="item in userList"
                  v-if="item.roleAlias != null && item.roleAlias.split(',').includes('customer_manager')"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="优化师:" v-if="$store.getters.userInfo.is_agency ===1">
              <el-select id="id-business-offer-queryForm-optimized" v-model="queryForm.optimized" clearable
                         filterable size="mini" placeholder="请选择用户" style="width:100%"
                         ref="sharedUserId" @visible-change="isShowSelectOptions" @change="searchForm">
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="searchConceal" :gutter="20">
          <el-col :span="5">
            <el-form-item label="设计师:">
              <el-select id="id-business-offer-queryForm-designer" v-model="queryForm.designer" clearable
                         filterable size="mini" placeholder="请选择用户" style="width:100%"
                         ref="sharedUserId" @visible-change="isShowSelectOptions" @change="searchForm">
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="内外订单:">
              <el-select id="id-business-offer-queryForm-sharedUserId" v-model="queryForm.isShared" clearable
                         filterable size="mini" placeholder="请选择用户" style="width:100%"
                         ref="sharedUserId" @visible-change="isShowSelectOptions" @change="searchForm">
                <el-option
                  label="内部"
                  :value="0">
                </el-option>
                <el-option
                  label="外部"
                  :value="1">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="素材审核:">
              <el-select id="id-business-offer-queryForm-auditCreative" v-model="queryForm.auditCreative" clearable
                         size="mini" placeholder="请选择素材审核" style="width:100%"
                         ref="auditCreative" @visible-change="isShowSelectOptions" @change="searchForm">
                <el-option
                  v-for="item in auditCreativeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="媒体:">
              <el-select id="id-business-offer-queryForm-platforms" v-model="queryForm.platforms"
                         clearable size="mini" placeholder="请选择媒体" style="width:100%"
                         ref="offerPlatform" @visible-change="isShowSelectOptions" @change="searchForm">
                <el-option
                  v-for="item in platformList"
                  :key="item.dictKey"
                  :label="item.dictValue"
                  :value="item.dictKey">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="searchConceal" :gutter="20">
          <el-col :span="5">
            <el-form-item label="操作系统:">
              <el-select id="id-business-offer-queryForm-os" v-model="queryForm.os" clearable size="mini"
                         placeholder="请选择操作系统" style="width:100%"
                         ref="os" @visible-change="isShowSelectOptions" @change="searchForm">
                <el-option
                  v-for="item in osList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="销售经理:">
              <el-select id="id-business-offer-queryForm-salesManager" v-model="queryForm.salesManager" clearable
                         filterable size="mini" placeholder="请选择销售经理" style="width:100%"
                         ref="salesManager" @visible-change="isShowSelectOptions" @change="searchForm">
                <el-option
                  v-for="item in userList"
                  v-if="item.roleAlias != null && item.roleAlias.split(',').includes('sales_manager')"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="创建人:">
              <el-select id="id-business-offer-queryForm-createUser" v-model="queryForm.createUser" clearable
                         filterable=" " size="mini" placeholder="请选择创建人" style="width:100%"
                         ref="offerPlatform" @visible-change="isShowSelectOptions" @change="searchForm">
                <el-option
                  v-for="item in userList"
                  v-if="item.status == 2 || (item.roleAlias != null && (item.roleAlias.split(',').includes('admin') || item.roleAlias.split(',').includes('operator') || item.roleAlias.split(',').includes('optimizer')))"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="用户:">
              <el-select id="id-business-offer-queryForm-sharedUserId" v-model="queryForm.sharedUserId" clearable
                         filterable size="mini" placeholder="请选择用户" style="width:100%"
                         ref="sharedUserId" @visible-change="isShowSelectOptions" @change="searchForm">
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="searchConceal" :gutter="20">
          <el-col :span="5">
            <el-form-item label="创建时间:">
              <el-date-picker
                v-model="queryForm.createDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                value-format="yyyy-MM-dd"
                unlink-panels
                size="mini"
                end-placeholder="结束日期"
                @change="searchForm">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <beetles-table class="beetlesTable" :option="option" :data="data" :table-loading="loading" :page.sync="page"
                   :view-name="'offer'"
                   ref="crud"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange"
                   @on-load="onLoad(page)"
    >
      <template slot-scope="{row}" slot="status">
        <div>
          <div v-if="row.status !== 3">
            <el-select v-model="row.status" @change="changeStatus($event,row)" size="mini"
                       :disabled="!((roles.admin || permission.offer_edit) && (row.originOfferId === -1)  && (row.status !== 3)) ">

              <el-option v-for="(item,index) in statusTableList()" :key="index" :value="item.value" :label="item.label"
                         :disabled="item.disabled">
              </el-option>
            </el-select>
          </div>
          <div v-if="row.status === 3">
            删除
          </div>
        </div>
      </template>
      <template slot-scope="{row}" slot="name">
        <div v-if="row.status != 0">
          <a href="javascript:void(0)" @click="openOcPage(row,'offer')">{{ row.name }}</a>
        </div>
        <div v-else>{{ row.name }}</div>
      </template>
      <template slot-scope="{row}" slot="platforms">
        <div style="display: flex;flex-wrap: wrap;">
          <div style="width: 20px;margin-right: 4px"
               v-for="(item,index) in platformLogo(row.androidPlatform,row.iosPlatform,row.websitePlatform)"
               :key="index">
            <img style="width: 100%" :src="item.url" :title="item.name">
          </div>
        </div>
      </template>
      <template slot-scope="{row}" slot="os">
        <div>
          <a v-show="row.androidAppUrl !== ''" style="margin-right: 5px;cursor: pointer"
             @click="openUrl(row.androidAppUrl)">
            <img style="width: 30%" src="/img/icon/android.png" alt="android"></a>
          <a v-show="row.iosAppUrl !== ''" style="cursor: pointer" @click="openUrl(row.iosAppUrl)">
            <img style="width: 30%" src="/img/icon/ios.png" alt="os">
          </a>
          <a v-show="row.websiteAppUrl !== '' && row.websiteAppUrl != '-1'" style="cursor: pointer"
             @click="openUrl(row.websiteAppUrl)">
            <img style="width: 30%" src="/img/icon/IE.png" alt="website">
          </a>
        </div>
      </template>
      <template slot-scope="{row}" slot="customerManager">
        <div>{{ getUserNames(row.customerManager) }}</div>
      </template>
      <template slot-scope="{row}" slot="salesManager">
        <div>{{ getUserNames(row.salesManager) }}</div>
      </template>
      <template slot-scope="{row}" slot="createUser">
        <div>{{ getUserNames(row.createUser) }}</div>
      </template>
      <template slot-scope="{row}" slot="opUsers">
        <div>{{ findOpUsers(row.opUsers) }}</div>
      </template>
      <template slot-scope="{row}" slot="designers">
        <div>{{ finddesigners(row.designers) }}</div>
      </template>
      <template slot="search" slot-scope="{size}">
        <div style="width:300px;display: flex;">
          <div style="margin-right: 5%;margin-left:5%;width: 12%; height: 32px;line-height: 32px; "> 状态:</div>
          <el-select :size="size" v-model="search.status" clearable>
            <el-option v-for="(item,index) in statusList" :key="index" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>

      </template>
      <template slot="menuLeft">
        <el-button type="success"
                   size="small"
                   icon="el-icon-download"
                   plain
                   :disabled="!(selectionList.length > 0)"
                   @click="handleExport">导 出
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   plain
                   v-if="roles.admin|| permission.offer_add"
                   @click="handleAdd">新 增
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="roles.admin|| permission.offer_delete"
                   :disabled="deletableSelectedList.length == 0"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="warning"
                   size="small"
                   icon="el-icon-s-promotion"
                   plain
                   v-if="roles.admin || permission.offer_share"
                   @click="handleShare">分 享
        </el-button>
        <el-button
          v-if="(roles.admin|| roles.designer_manager)"
          :disabled="!(selectionList != null && selectionList.length == 1)"
          type="warning"
          size="small"
          plain
          @click="openTagsModel"
        >
          标签模板
        </el-button>
        <el-badge v-if="(roles.admin|| roles.operator) && userInfo.is_agency === 1" :value="confictedOfferNum"
                  class="item">
          <el-button type="danger"
                     size="small"
                     icon="el-icon-suitcase"
                     plain
                     v-if="(roles.admin|| roles.operator) && userInfo.is_agency === 1"
                     @click="handleFixConflict">订单冲突处理
          </el-button>
        </el-badge>

      </template>
      <template slot-scope="{type,size,row}" slot="menu">
        <el-tooltip content="查看" placement="top">
          <el-button size="small" icon="el-icon-view" type="text" @click="checkRow(row)"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="编辑" placement="top">
          <el-button icon="el-icon-edit" type="text" @click="editRow(row)"
                     :disabled="!((roles.admin|| permission.offer_edit)&&row.originOfferId === -1  && (row.status !== 3))"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="通知配置" placement="top">
          <el-button icon="el-icon-setting" type="text" @click="noticeConf(row)"
                     :disabled="!(roles.admin || roles.agc_customer_manager)"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="删除" placement="top">
          <el-button icon="el-icon-delete" type="text" @click="rowDel(row)"
                     :disabled="!((roles.admin|| permission.offer_delete) && (row.status !== 1 && row.status !== 3))"></el-button>
        </el-tooltip>
      </template>
    </beetles-table>
    <offer-edit :title="offerDialogType" :offerStatus="offerStatus" :dialogVisible="offerDialogOpen"
                :dataList="editList" @close-dialog="closeOfferDialog" :confirm-to-share="confirmToShare"></offer-edit>

    <!--  订单冲突弹窗  -->
    <offer-conflict-edit :dialogVisible="conflictDialogOpen"
                         @close-dialog="conflictCloseDialog"
                         @count-conflicted-offer="countConflictedOffer"></offer-conflict-edit>

    <!-- 通知配置弹窗 -->
    <template-conf :dialogVisible="templateAdd" @closeAddDialog="closeAddDialog"
                   :offerID="offerId" @allNotice="allNotice"
                   :globalConf="globalConf" :globalSwitch="globalSwitch"></template-conf>
    <div newPageLink></div>
    <el-drawer
      title="订单分享"
      size="80%"
      :visible.sync="shareDialog"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      ref="drawer"
    >
      <el-divider></el-divider>
      <div class="drawer__content">
        <share-re v-if="shareDialog" :offer-id="this.selectionList[0].id" ref="shareRef"></share-re>
        <div class="drawer__footer">
          <el-button type="primary" size="mini" @click="saveShare">保存</el-button>
          <el-button size="mini" @click="shareDialog=false">取消</el-button>

        </div>
      </div>
    </el-drawer>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  changeStatus,
  getPlatform,
  getGlobalConfiguration
} from "@/api/business/offer";
import {getAllUser} from "@/api/user"
import {count} from "@/api/business/offerConflict";
import {mapGetters} from "vuex";
import offerEdit from "./components/offerEdit"
import offerConflictEdit from "./components/offerConflictEdit"
import {OC_LOGIN_URL} from "@/const/urlConst"
import {getToken} from '@/util/auth';
import {genTokenKey} from '@/api/user';
import website from "@/config/website";
import store from '@/store'
import TemplateConf from "@/views/system/components/templateConf";
import {checkOfferNotice, getConfSwitch} from "@/api/business/thirdpartyconf";
import {exportExcel2} from "@/util/util";
import Moment from 'moment';
import {transformObjectList, findObject} from "@/util/util";
import {getSysDictList} from "@/api/system/dict";
import beetlesTable from "@/components/basic-components/beetles-table"
import CsCell from "@/components/CsCell/CsCell";
import shareRe from "@/views/business/shareRe";

export default {
  name: 'offer',
  components: {
    beetlesTable,
    TemplateConf,
    offerEdit,
    offerConflictEdit,
    CsCell,
    shareRe
  },
  data() {
    let checkOfferId = (rule, value, callback) => {
      const shortReg = /^\d{3,20}$/;
      if (value !== '' && !shortReg.test(value)) {
        callback(new Error('请输入3-20位数字!'))
      } else {
        callback()
      }
    };
    return {
      customerLevelList: [{value: "T1"}, {value: "T2"}, {value: "T3"}],
      globalConf: [],
      globalSwitch: '',
      offerNoticeConf: [],
      offerId: '',
      templateAdd: false,
      upIcon: 'el-icon-arrow-down',
      searchIcon: 'el-icon-search',
      emptyIcon: 'el-icon-delete',
      searchConceal: false,
      confirmToShare: 0,  //状态为0时分享界面显示确认分享按钮，为1时隐藏确认分享按钮
      confictedOfferNum: 0, //冲突订单的数量
      offerStatus: '',//offer状态
      editList: '',//编辑数据
      offerDialogType: '',//打开弹出框的类型
      offerDialogOpen: false,
      conflictDialogOpen: false,
      search: {},
      queryForm: {
        id: '',
        platforms: '',
        status: '',
        name: null,
        customerName: null,
        productName: null,
        salesManager: '',
        customerManager: '',
        createUser: '',
        sharedUserId: '',
        auditCreative: '',
        createDate: '',
        createDateRange: '',
        os: '',
        customerLevel: '',
        optimized: '',
        designer: '',
        isShared: ''
      },
      form: {},
      rules: {
        id: [{required: false, validator: checkOfferId, trigger: 'change'}],
      },
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      auditCreativeList: [
        {label: '不审核', value: 0},
        {label: '审核', value: 1},
      ],
      osList: [
        {label: 'IOS', value: 'ios'},
        {label: 'Android', value: 'android'},
        {label: 'Website', value: 'website'},
      ],
      statusList: [
        {label: '草稿', value: 0},
        {label: '活跃', value: 1},
        {label: '停止', value: 2},
        {label: '删除', value: 3},
      ],
      userList: [],
      confSwitch: '',
      checkOfferConf: '',
      selectionList: [],
      platformList: [],
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        //excelBtn: true,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: "订单名称",
            prop: "name",
            fixed: true,
            rules: [{
              required: true,
              message: "请输入订单名称",
              trigger: "blur"
            }],
          },
          {
            label: "订单ID",
            prop: "id"
          },
          // {
          //   label: "等级",
          //   prop: "level"
          // },
          {
            label: "客户",
            prop: "customerName",
            showColumn: store.getters.userInfo.is_agency === 1,
            overHidden: true,
            searchSize: "mini",
          },
          {
            label: "客户等级",
            prop: "customerLevel",
            hide: store.getters.userInfo.is_agency === 0,
          },
          {
            label: "产品名",
            prop: "productName",
            rules: [{
              required: true,
              message: "请输入产品名",
              trigger: "blur"
            }],
            overHidden: true,
          },
          {
            label: "状态",
            prop: "status",
            dicData: [
              {label: '草稿', value: 0},
              {label: '活跃', value: 1},
              {label: '停止', value: 2},
              {label: '删除', value: 3}
            ],
            rules: [{
              required: false,
              message: "请输入状态",
              trigger: "blur"
            }],
            slot: true,
          },
          {
            label: "客户经理",
            prop: "customerManager",
            type: 'select',
            dicUrl: '/api/blade-user/select-user?roleAlias=customer_manager',
            props: {
              label: "realName",
              value: "id"
            },
            dataType: 'string',
            rules: [{
              required: true,
              message: "请选择客户经理",
              trigger: "blur"
            }],
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
            hide: store.getters.userInfo.is_agency === 0,
          },
          {
            label: "优化师",
            prop: "opUsers",
            hide: store.getters.userInfo.is_agency === 0,
          },
          {
            label: "设计师",
            prop: "designers",
            hide: store.getters.userInfo.is_agency === 0,
          },
          {
            label: "账户",
            prop: "accounts",
          },
          {
            label: "内外订单",
            prop: "isShared",
            type: 'select',
            dicData: [
              {label: '内部', value: 0},
              {label: '外部', value: 1},
            ],
            hide: false,
          },
          {
            label: "素材审核",
            prop: "auditCreative",
            type: 'select',
            dicData: [
              {label: '审核', value: 1},
              {label: '不审核', value: 0}
            ],
            rules: [{
              required: true,
              message: "请输入是否审核素材",
              trigger: "blur"
            }]
          },
          {
            label: "媒体",
            prop: "platforms",
            type: 'select',
            multiple: true,
            slot: true,
            dataType: 'string',
            dicData: [],
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            searchMultiple: true,
          },
          {
            label: "操作系统",
            prop: "os",
            type: 'select',
            multiple: true,
            dicData: [],
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            slot: true,
            dataType: 'string',
            rules: [{
              required: true,
              message: "请输入操作系统",
              trigger: "blur"
            }]
          },
          {
            label: "备注",
            prop: "remark",
          },
          {
            label: "销售经理",
            prop: "salesManager",
            type: 'select',
            dicUrl: '/api/blade-user/select-user?roleAlias=sales_manager',
            props: {
              label: "realName",
              value: "id"
            },
            dataType: 'string',
            rules: [{
              required: true,
              message: "请选择销售经理",
              trigger: "blur"
            }],
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
            hide: store.getters.userInfo.is_agency === 0,
          },
          {
            label: "创建人",
            prop: "createUser",
            dicUrl: "/api/blade-user/get-user-select",
            props: {
              label: "realName",
              value: "id"
            },
            overHidden: true,
            addDisplay: false
          },
          {
            label: "创建时间",
            prop: "createTime",
            overHidden: true,
          },
        ]
      },
      data: [],
      currOpRowId: '',
      // 分享弹窗
      // -----------------man------------------------
      shareDialog: false,
      activeName: 'inside',
      options: [{
        value: '选项1',
        label: '黄金糕'
      }, {
        value: '选项2',
        label: '双皮奶'
      }, {
        value: '选项3',
        label: '蚵仔煎'
      }, {
        value: '选项4',
        label: '龙须面'
      }, {
        value: '选项5',
        label: '北京烤鸭'
      }],
      value: '',
      multipleSelection: [],
      userTableData: [],
    };

  },
  activated() {
    this.$route.meta.isBack = false
  },
  computed: {
    ...mapGetters(["permission", "userInfo", "roles"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.offer_add, false),
        viewBtn: this.vaildData(this.permission.offer_view, false),
        delBtn: this.vaildData(this.permission.offer_delete, false),
        editBtn: this.vaildData(this.permission.offer_edit, false),
        excelBtn: this.vaildData(this.roles.admin || this.roles.operator, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    deletableSelectedList() {
      return this.getDeletableSelectedList();
    },
  },
  created() {
    getGlobalConfiguration().then(res => {
      if (res.data.data.length > 0) {
        this.globalConf = res.data.data[0].offerNoticeRoles.split(',')
        this.globalSwitch = res.data.data[0].offerNotice
      }
    })
    getSysDictList('platforms,app_os').then(map => {
      this.platformList = map['platforms'];
      let column = findObject(this.option.column, 'platforms', 'prop')
      if (column != null) {
        column.dicData = map['platforms'];
      }
      column = findObject(this.option.column, 'os', 'prop')
      if (column != null) {
        column.dicData = map['app_os'];
      }
    });
    getAllUser({statusList: '0,1,2'}).then(res => {
      this.userList = res.data.data
    });
    getConfSwitch().then(res => {
      this.confSwitch = res.data.data
    })
    checkOfferNotice().then(res => {
      this.offerNoticeConf = res.data.data
    })
    this.buildSearch();
  },
  mounted() {
    this.countConflictedOffer();//需要触发的函数
    this.$bus.on("parameterName", value => {
      this.confSwitch = value
    });
  },

  methods: {
    //跳转订单模板
    openTagsModel() {
      if (this.selectionList.length === 0 || this.selectionList.length > 1) {
        this.$message.warning("请选择一张订单添加标签模板");
        return;
      }
      // this.$router.push({name: '全局配置', params: {config: 'tags', offerId: this.selectionList[0].id}})
      this.$router.push({name: '全局配置', params: {config: 'newtag', offerId: this.selectionList[0].id}})
    },
    noticeConf(row) {
      this.offerId = row.id
      getGlobalConfiguration().then(res => {
        this.globalConf = res.data.data[0].offerNoticeRoles.split(',')
        this.globalSwitch = res.data.data[0].offerNotice
      })
      this.templateAdd = true
    },
    closeAddDialog() {
      this.templateAdd = false
    },
    allNotice() {
      checkOfferNotice().then(res => {
        this.offerNoticeConf = res.data.data
      })
    },
    getUserNames(userIds) {
      if (userIds != null && userIds != '' && this.userList != null && this.userList.length > 0) {
        let list = [];
        let ids = ('' + userIds).split(',');
        this.userList.forEach(user => {
          if (ids.includes(user.id)) {
            list.push(user.realName);
          }
        })
        return list.join(',');
      }
      return userIds;
    },
    unfoldIcon() {
      if (this.upIcon === 'el-icon-arrow-down') {
        this.upIcon = 'el-icon-arrow-up'
        this.searchConceal = true
      } else {
        this.upIcon = 'el-icon-arrow-down'
        this.searchConceal = false
      }
    },
    isShowSelectOptions(isShowSelectOptions) {
      if (!isShowSelectOptions) this.$refs.offerPlatform.blur();
      if (!isShowSelectOptions) this.$refs.offerStatus.blur();
    },
    buildSearch() {
      let query = {...this.queryForm};
      // 改为多选
      // query.customerLevel = query.customerLevel.join(',')
      // query.status = query.status.join(',')
      // query.customerManager = query.customerManager.join(',')
      // query.optimized = query.optimized.join(',')
      // query.designer = query.designer.join(',')
      // query.isShared = query.isShared.join(',')
      // query.auditCreative = query.auditCreative.join(',')
      // query.platforms = query.platforms.join(',')
      // query.os = query.os.join(',')
      // query.salesManager = query.salesManager.join(',')
      // query.createUser = query.createUser.join(',')
      // query.sharedUserId = query.sharedUserId.join(',')
      delete query.createDateRange;
      if (this.queryForm.createDateRange != null && this.queryForm.createDateRange.length == 2) {
        query.createDate = Moment(this.queryForm.createDateRange[0]).format('YYYY-MM-DD') + ',' + Moment(this.queryForm.createDateRange[1]).format('YYYY-MM-DD');
      }
      this.query = query;
    },
    //搜索按钮函数
    searchForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buildSearch();
          this.page.currentPage = 1
          this.onLoad(this.page)
        }
      });
    },
    //清楚按钮函数
    emptyForm() {
      this.queryForm = {
        id: '',
        platforms: null,
        status: null,
        name: null,
        customerName: null,
        productName: null,
        salesManager: null,
        customerManager: null,
        createUser: null,
        sharedUserId: null,
        auditCreative: '',
        createDate: '',
        createDateRange: [],
        os: '',
        designer: '',
        optimized: '',
        customerLevel: ''
      }
      this.searchForm();
    },

    getTokenKeyInfo(row, type) {
      if (type == 'offer') {
        return JSON.stringify({offerId: row.id});
      }
      return '';
    },
    openOcPage(row, type) {
      let ocTokenKey = '';
      let headers = {};
      headers[website.tokenHeader] = getToken();
      genTokenKey({
        sync: true,
        headers: headers,
        info: this.getTokenKeyInfo(row, type),
        success: (data) => {
          ocTokenKey = data.tokenKey;
        },
        error: () => {
        }
      });
      if (ocTokenKey == '') {
        this.$message.error('获取信息错误，无法正确跳转到订单中心');
        return;
      }
      let eleList = document.querySelectorAll('div[newPageLink]');
      let content = eleList[0];
      let linkEle = document.createElement("a");
      content.appendChild(linkEle);

      // 利用URL.createObjectURL()方法为a元素生成blob URL
      linkEle.target = '_blank';
      linkEle.href = OC_LOGIN_URL + '?tokenKey=' + ocTokenKey;
      linkEle.click();
      linkEle.remove();
    },
    // 统计冲突数量
    countConflictedOffer() {
      count().then(res => {
        this.confictedOfferNum = res.data.data;
      });
    },

    //打开 安卓,ios链接
    openUrl(url) {
      if (url.startsWith('http://') || url.startsWith('https://')) {
        window.open(url, '_blank')
      } else {
        window.open('https://' + url, '_blank')
      }
    },

    //修改状态
    changeStatus(val, row) {
      if (!this.offerNoticeConf.includes(row.id) && (this.confSwitch === "100" || this.confSwitch === 100)) {
        this.offerId = row.id
        this.templateAdd = true
        this.$message({
          type: 'warning',
          message: "请配置为此订单添加通知配置"
        })
        getGlobalConfiguration().then(res => {
          this.globalConf = res.data.data[0].offerNoticeRoles.split(',')
          this.globalSwitch = res.data.data[0].offerNotice
        })
        this.refreshChange()
        return
      }
      changeStatus(row.id, val).then(res => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: '状态修改成功!'
          })
          this.refreshChange()
        }
      })
      this.refreshChange()
    },
    //table 状态
    statusTableList() {
      return [
        {label: '草稿', value: 0, disabled: true},
        {label: '活跃', value: 1},
        {label: '停止', value: 2}
      ]
    },
    //分享mangai
    handleShare() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      // if (this.selectionList.length !== 1) {
      //   this.$message.warning("只能选择一条数据")
      //   return
      // }
      if (this.selectionList[0].status != 1) {
        this.$message.warning("当前订单不是活跃状态，不能被分享")
        return;
      }
      this.confirmToShare = 0
      // this.$router.push({path: '/business/share', query: {offerId: this.selectionList[0].id}})
      // 新抽屉样式
      this.shareDialog = true
    },

    //查看
    checkRow(row) {
      this.currOpRowId = row.id;
      getDetail(row.id).then(res => {
        this.editList = res.data.data;
      });
      this.offerDialogType = 'check'
      this.offerDialogOpen = true
      this.confirmToShare = 1
    },
    //编辑
    editRow(row) {
      this.currOpRowId = row.id;
      getDetail(row.id).then(res => {
        this.editList = res.data.data;
        this.offerStatus = res.data.data.status
      });
      this.offerDialogType = 'edit'
      this.offerDialogOpen = true
    },
    //新增
    handleAdd() {
      this.offerDialogType = 'add'
      this.offerStatus = ''
      this.offerDialogOpen = true
    },
    //dialog关闭回调
    closeOfferDialog() {
      this.offerDialogOpen = false
      this.offerStatus = 'close'
      this.onLoad(this.page);
    },

    // offer冲突处理弹窗打开
    handleFixConflict() {
      this.conflictDialogOpen = true;
    },
    //offer冲突处理关闭回调
    conflictCloseDialog() {
      this.conflictDialogOpen = false
      this.onLoad(this.page);
    },

    //媒体 logo
    platformLogo(androidPlatform, iosPlatform, websitePlatform) {
      let androidlist = androidPlatform.split(',')
      let iosroidlist = iosPlatform.split(',')
      let websiteList = websitePlatform.split(',')
      let logoList = []
      androidlist = Array.from(new Set([...androidlist, ...iosroidlist, ...websiteList]))
      androidlist.map(item => {
        switch (item) {
          case 'google':
            logoList.push({name: 'google', url: '/img/icon/google-icon.png'});
            return
          case 'facebook':
            logoList.push({name: 'facebook', url: '/img/icon/facebook-icon.png'});
            return
          case 'bigo':
            logoList.push({name: 'bigo', url: '/img/icon/bigo-icon.png'});
            return
          case 'tiktok':
            logoList.push({name: 'tiktok', url: '/img/icon/tiktok-icon.png'});
            return
          case 'kwai':
            logoList.push({name: 'kwai', url: '/img/icon/kwai-icon.png'});
            return
          case 'eagllwin':
            logoList.push({name: 'eagllwin', url: '/img/icon/eagllwin-icon.png'});
            return
        }
      })

      return logoList
    },
    rowDel(row) {
      if (row.originOfferId === -1 && row.status !== 0) {
        if (!this.offerNoticeConf.includes(row.id) && (this.confSwitch === 100 || this.confSwitch === "100")) {
          this.templateAdd = true
          this.$message({
            type: 'warning',
            message: "请先为此订单配置通知配置后方可删除"
          })
          getGlobalConfiguration().then(res => {
            this.globalConf = res.data.data[0].offerNoticeRoles.split(',')
            this.globalSwitch = res.data.data[0].offerNotice
          })
          return
        }
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },

    getDeletableSelectedList() {
      if (this.selectionList == null) {
        return [];
      }
      for (let i = 0; i < this.selectionList.length; i++) {
        if (this.selectionList[i].status == 1 || this.selectionList[i].status == 3) {
          return [];
        }
        // if (!this.offerNoticeConf.includes(this.selectionList[i].id) && (this.confSwitch ===100 || this.confSwitch === "100")){
        //   return [];
        // }
      }
      return this.selectionList;
    },
    handleDelete() {
      for (let i = 0; i < this.selectionList.length; i++) {
        if (this.selectionList[i].status == 1 || this.selectionList[i].status == 3) {
          this.$message({
            type: 'warning',
            message: "活跃或已被删除的订单，不允许删除"
          })
          return;
        }
      }
      for (let i = 0; i < this.selectionList.length; i++) {
        if (!this.offerNoticeConf.includes(this.selectionList[i].id) && (this.confSwitch === 100 || this.confSwitch === "100")) {
          this.$message({
            type: 'warning',
            message: "存在未配置通知配置的订单，不允许删除"
          })
          return;
        }

      }
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      params.offerType = "admin,owner,manager,shared"
      if (this.userList == null || this.userList.length == 0) {
        await getAllUser({statusList: '0,1,2'}).then(res => {
          this.userList = res.data.data
        });
      }
      await getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
      this.countConflictedOffer();
    },
    getRowClassName({row}) {
      if (row.id == this.currOpRowId) {
        return "current-op-row";
      } else {
        return "";
      }
    },
    handleExport() {
      this.$confirm("是否导出订单数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let tableData = {
          title: null,
          headers: [],
          rowList: [],
          bottom: [],
        };
        tableData.headers.push({
          data: '订单ID',
          style: 'text-align: right; background-color: #bebebe; font-weight: bold;'
        });
        tableData.headers.push({
          data: '订单名称',
          style: 'text-align: right; background-color: #bebebe; font-weight: bold;'
        });
        tableData.headers.push({data: '客户', style: 'text-align: right; background-color: #bebebe; font-weight: bold;'});
        tableData.headers.push({
          data: '产品名',
          style: 'text-align: right; background-color: #bebebe; font-weight: bold;'
        });
        tableData.headers.push({data: '账户', style: 'text-align: right; background-color: #bebebe; font-weight: bold;'});
        tableData.headers.push({data: '内外', style: 'text-align: right; background-color: #bebebe; font-weight: bold;'});
        tableData.headers.push({
          data: '素材审核',
          style: 'text-align: right; background-color: #bebebe; font-weight: bold;'
        });
        tableData.headers.push({data: '媒体', style: 'text-align: right; background-color: #bebebe; font-weight: bold;'});
        tableData.headers.push({
          data: '操作系统',
          style: 'text-align: right; background-color: #bebebe; font-weight: bold;'
        });
        tableData.headers.push({data: '备注', style: 'text-align: right; background-color: #bebebe; font-weight: bold;'});
        tableData.headers.push({data: '状态', style: 'text-align: right; background-color: #bebebe; font-weight: bold;'});
        tableData.headers.push({
          data: '销售经理',
          style: 'text-align: right; background-color: #bebebe; font-weight: bold;'
        });
        tableData.headers.push({
          data: '客户经理',
          style: 'text-align: right; background-color: #bebebe; font-weight: bold;'
        });
        tableData.headers.push({
          data: '创建人',
          style: 'text-align: right; background-color: #bebebe; font-weight: bold;'
        });
        tableData.headers.push({
          data: '创建时间',
          style: 'text-align: right; background-color: #bebebe; font-weight: bold;'
        });
        console.log(this.selectionList)
        this.selectionList.forEach(row => {
          console.log(row)
          let colList = [];
          let os = []
          if (row.androidAppUrl !== '') os.push("Android")
          if (row.iosAppUrl !== '') os.push("IOS")
          if (row.websiteAppUrl !== '') os.push("Website")

          let androidList = row.androidPlatform.split(',')
          let iosList = row.iosPlatform.split(',')
          let websiteList = row.websitePlatform.split(',')
          let platforms = Array.from(new Set([...androidList, ...iosList, ...websiteList]))
          let auditCreative = ''
          if (row.auditCreative === 1) {
            auditCreative = "是"
          }
          if (row.auditCreative === 0) {
            auditCreative = "否"
          }
          colList.push({data: row.id, style: 'text-align: right; vnd.ms-excel.numberformat: @'});
          colList.push({data: row.name, style: 'text-align: right;'});
          colList.push({data: row.customerName, style: 'text-align: right;'});
          colList.push({data: row.productName, style: 'text-align: right;'});
          colList.push({data: row.accounts, style: 'text-align: right;'});
          colList.push({data: row.$isShared, style: 'text-align: right;'});
          colList.push({data: auditCreative, style: 'text-align: right;'});
          colList.push({data: platforms.filter(p => p).join(","), style: 'text-align: right;'});
          colList.push({data: os.join(","), style: 'text-align: right;'});
          colList.push({data: row.remark, style: 'text-align: right;'});
          colList.push({data: row.$status, style: 'text-align: right;'});
          colList.push({data: row.$salesManager, style: 'text-align: right;'});
          colList.push({data: row.$customerManager, style: 'text-align: right;'});
          colList.push({data: row.$createUser, style: 'text-align: right;'});
          colList.push({data: row.createTime, style: 'text-align: right;'});
          tableData.rowList.push(colList);
        });
        exportExcel2(tableData.title, tableData.headers, tableData.rowList, tableData.bottom, '订单数据表');
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    saveShare() {
      this.$refs.shareRef.$refs.shareAdvRef.confirmShare2adv()
      this.shareDialog = false
    },
    // marco methods
    // 查找优化师
    findOpUsers(val) {
      if (val === '') return ''
      const users = val.split(',')
      // 过滤，遍历，拼装成字符串
      return this.userList.filter(user => users.includes(user.id)).map(item => item.realName).join(',')
    },
    // 查找设计师
    finddesigners(val) {
      if (val === '') return ''
      const users = val.split(',')
      // 过滤，遍历，拼装成字符串
      return this.userList.filter(user => users.includes(user.id)).map(item => item.realName).join(',')
    }
  }
};
</script>

<style lang="scss" scoped>
.search_form {
  /deep/ .el-form-item {
    margin-bottom: 0;
  }
}

/deep/ .current-op-row {
  background-color: #f5dab1;
}

/deep/ [searchform] [searchitem] .el-input__inner {
  height: 24px;
  margin-left: -12px;
  width: 195px;
}

/deep/ [searchform] [searchitem] .el-form-item__label {
  text-align: left;
  height: 24px;
}

/deep/ .el-form-item__error {
  margin-top: -50px;
}

/deep/ [searchform] [searchitem] .el-form-item {
  margin: 0px;
  width: unset;
  height: 24px;
}

/deep/ [searchform] [searchitem] .el-form-item__label {
  width: 70px;
  margin: unset;
  height: 24px;
  margin-top: -12px;
}

/deep/ [searchform] [searchitem] .el-form-item__content {
  margin-left: unset;
  width: unset;
  height: 24px;
  line-height: unset;
}

/deep/ [searchform] [searchitem] .el-input--suffix {
  height: 24px;
  margin-left: -12px;
  width: 190px;
}

/deep/ [searchform] [searchitem] .el-input__suffix {
  margin-top: -6px;
}

.drawer__content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  height: 90%;

  .drawer__body {
    height: 80%;
    width: 100%;
  }

  .drawer__footer {
    margin-top: 20px;
    z-index: 9999;
  }
}

::v-deep .el-radio-button__inner {
  padding: 7px 35px;
}
</style>
